package com.xl.sst.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xl.sst.biz.UsersBiz;
import com.xl.sst.utill.JSMSUtil;
import com.xl.sst.vo.Users;
import cn.jsms.api.SendSMSResult;
@Controller
@RequestMapping("/user")
public class UsersController {
	@Resource
	private UsersBiz usersBiz;
	
	/**
	 * 用户登录
	 * @param users
	 * @param req
	 * @return 0 成功  1账号或密码错误 
	 */
	@RequestMapping("/login.do")
	@ResponseBody
	public Integer login(@RequestBody Users users,HttpServletRequest req){
		UsernamePasswordToken token = new UsernamePasswordToken(users.getPhone(), users.getPassword(), null);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
			return 0;
		}catch(Exception e){
			return 1;
		}
	}
	/**
	 * 用户注册
	 * @param users
	 * @param session
	 * @param req
	 * @return 0 注册成功  1注册失败 2验证码错误
	 */
	@RequestMapping("/register.do")
	@ResponseBody
	public Integer register(Users users,HttpSession session, HttpServletRequest req){
		users.setSproperty(0);//代表个人注册
		int a=usersBiz.insertUser(users,session);//a==0 注册成功  a==1注册失败（用户名重复）  a==2 验证码不正确
		return a;
		
	}
	
	/**
	 * 企业注册
	 * @param users
	 * @param session
	 * @param req
	 * @return 0 注册成功  1注册失败 2验证码错误
	 */
	@RequestMapping("/register1.do")
	@ResponseBody
	public Integer register1(Users users,HttpSession session, HttpServletRequest req){
		users.setSproperty(1);//代表企业注册
		int a=usersBiz.insertUser(users,session);//a==0 注册成功  a==1注册失败（用户名重复）  a==2 验证码不正确
		return a;
		
	}
	/**
	 * 验证手机号码是否已经注册
	 * @param phone
	 * @return 0 没有注册 1已经注册
	 */
	//验证用户名是否唯一
	@RequestMapping("/onlyphone.do")
	@ResponseBody
	public Integer onlyphone(String phone){
		Users user = usersBiz.getUser(phone);
		if(user!=null) {
			return 1;//已经注册
		}else {
			return 0;//没有注册
		}
		
	}
	
	/**
	 * 发送验证码
	 * @param phone
	 * @param session
	 * @return ture 发送成功  false 发送失败
	 */
	@RequestMapping("/sendVerifyCode.do")
	public @ResponseBody boolean sendVerifyCode(String phone, HttpSession session) {
		Integer number = (int) (Math.random() * (9999 - 1000 + 1)) + 1000; //生成四位随机数
		session.setAttribute("yzm",number.toString()); //把验证码放进session中
		SendSMSResult smsResult = JSMSUtil.sendTemplateSmsToUser(35990, phone, String.valueOf(number), "鹿客帮");//参数1 模板代号 2手机号码 3消息标题      
		if (smsResult.isResultOK()) {
			return true;
		} else {
			return false;
		}
	}
	
}
